<template>
  <el-drawer
    size="50%"
    title="发送邮件"
    direction="rtl"
    :model-value="true"
    :before-close="handleCancel"
  >
    <div class="form-wrapper">
      <el-form
        class="custom-form"
        ref="form"
        :rules="rules"
        :model="form"
        label-width="80px"
        :disabled="readOnly"
      >
        <el-form-item label="组件名称" prop="name">
          <el-input
            class="custom-input custom-input-name"
            v-model.trim="form.name"
            type="text"
            maxlength="15"
            :show-word-limit="true"
          >
          </el-input>
        </el-form-item>
        <!-- <el-form-item label="发件人" prop="configId">
          <el-select
            v-model="form.configId"
            @change="handleEmailFromChange"
            placeholder="选择发件人"
          >
            <el-option
              v-for="item in emailConfigList"
              :key="item.id"
              :label="item.nickName"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->

        <!-- <el-form-item label="收件人" prop="to">
          <el-autocomplete
            v-model="form.to"
            value-key="propertyName"
            :fetch-suggestions="querySearch"
            placeholder="请输入收件人"
            @select="handleSelect"
          ></el-autocomplete>
        </el-form-item> -->

        <el-form-item label="选择模板" prop="content">
          <el-select
            v-model="form.emailModuleId"
            placeholder="请选择模板"
            @change="emailIdsChange()"
          >
            <el-option
              v-for="item in emailModuleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="模板标题" prop="title">
          <el-input v-model="form.title" placeholder="模板标题" />
        </el-form-item>

        <!-- <div v-if="form.keysList.length">
          <el-form-item
            v-for="(item, idx) in form.keysList"
            :key="idx"
            :label="item.name"
            prop="content"
          >
            <el-autocomplete
              class="custom-input custom-input-name"
              v-model="item.key"
              value-key="name"
              @click.left="index = idx"
              :fetch-suggestions="querySearch"
              placeholder="请输入属性值"
              @select="setExpression"
            ></el-autocomplete>
          </el-form-item>
        </div> -->

        <el-form-item>
          <set-variable-pub
            v-if="isDefault"
            :isCareat="isCareat"
            :domData="domData"
            @subRuleForm="subRuleForm"
          ></set-variable-pub>
        </el-form-item>

        <!--        <el-form-item label="模板内容">-->
        <!--          <quill-editor-->
        <!--            ref="templateEditor"-->
        <!--            content-type="html"-->
        <!--            v-model:content="form.content"-->
        <!--            :disabled="readOnly"-->
        <!--            theme="snow"-->
        <!--            toolbar="full">-->
        <!--          </quill-editor>-->
        <!--          rich-text: {{form.initialContent}}-->
        <!--          <rich-text v-model="form.initialContent"></rich-text>-->
        <!--        </el-form-item>-->

        <el-form-item label="模板内容">
          <!--          rich-editor: {{form.initialContent}}-->
          <rich-editor
            :value="form.initialContent"
            @change="handleEditorChange"
            ref="richEditor"
          ></rich-editor>
        </el-form-item>
      </el-form>
      <div class="form-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="formValidate">确定</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import CanvasApi from "@/api/canvasApi";
import { QuillEditor } from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
// import { getEmailConfig } from "../../api/system";

import RichEditor from "@/components/RichEditor.vue";
import { NodeDrawerDataModel } from "@/views/workTable/dataModel/NodeDrawerDataModel";
export default {
  components: {
    QuillEditor,
    RichEditor,
  },
  props: {
    dialogData: Object,
    addNodeEventData: Object,
    readOnly: Boolean,
  },
  emits: ["cancel", "confirm"],

  data() {
    return {
      isDefault: false,
      isCareat: true,
      index: "",
      emailModuleList: [],
      valueList: [],
      // emailConfigList: [],
      fromModel: null,
      domData: {
        content: "",
        data: {},
      },
      form: {
        name: "发送邮件",
        configId: "",
        from: "",
        fromUser: "",
        password: "",
        host: "",
        port: "",
        to: "{{$_user.$_email}}",
        title: "",
        content: "<p></p>",
        initialContent: "<p></p>",
        emailModuleId: "",
        keysList: [], // 变量key
        data: {}, // 用来回显的数据
      },
      reachType: 3,
      rules: {
        configId: [
          {
            required: true,
            trigger: ["change"],
            validator: (rule, val, callback) => {
              if (val) {
                callback();
              } else {
                callback(new Error("请检查发件人账户字段"));
              }
            },
          },
        ],
        to: [
          {
            required: true,
            message: "请输入收件人账户",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入名称",
          },
        ],
      },
    };
  },

  async mounted() {
    // await this.getEmailConfig();
    await this.getEmailTemplate();
    this.getValueList();
    this.recoverFromNodeData();
  },

  methods: {
    // async getEmailConfig() {
    //   const rs = await getEmailConfig({ size: -1 });
    //   if (rs.code === 200) {
    //     this.emailConfigList = rs.payload;
    //   }
    // },

    // handleEmailFromChange(val) {
    //   const emailConfig = this.emailConfigList.find((item) => item.id === val) || {};
    //   this.form.from = emailConfig.account;
    //   this.form.fromUser = emailConfig.nickName;
    //   this.form.password = emailConfig.password;
    //   this.form.host = emailConfig.host;
    //   this.form.port = emailConfig.port;
    // },

    getValueList() {
      this.valueList = [
        ...this.$store.state.event.eventObj.property,
        ...this.$store.state.event.eventObj.event,
        ...this.$store.state.event.publicEvent,
      ];
    },

    recoverFromNodeData() {
      if (!this.dialogData || !Object.keys(this.dialogData).length) {
        return;
      }

      const _reachBody = JSON.parse(this.dialogData.reachBody);
      this.form = _reachBody;
      this.form.title = _reachBody.title;
      this.form.initialContent = _reachBody.initialContent;

      this.isCareat = false;
      this.emailIdsChange(true);
    },

    subRuleForm(form) {

      // ruleForm.data = form

      this.form.data = form;
      let initialContent = this.form.initialContent;
      for (let item in form) {
        // debugger;
        //
        if (form[item].value) {
          // debugger
          let key = new RegExp(`{{${item}.DATA}}`, "g");

          initialContent = initialContent.replace(key, form[item].value);
        }
        //
      }

      this.form.content = initialContent;

    },

    // 输入框推荐内容
    querySearch(queryString, cb) {
      let results = queryString
        ? this.valueList.filter((item) => {
            return (
              (item.propertyName &&
                item.propertyName.toLowerCase().indexOf(queryString) !== -1) ||
              (item.name && item.name.toLowerCase().indexOf(queryString) !== -1)
            );
          })
        : this.valueList;
      cb(results);
    },

    // 点输入框提示内容触发
    handleSelect(item) {

      this.form.to = `{{$_user.${item.propertyKey}}}`;
    },

    // 设置表达式
    setExpression(item) {

      // 先等待index赋值
      this.$nextTick(() => {
        this.form.keysList[this.index].key = `{{$_user.${item.propertyKey}}}`;
      });
    },

    emailIdsChange(isEdit) {
      // debugger
      const regex = /\{{(.+?)\}}/g; // {{}} 匹配双花括号
      let variableList = [];
      let targetEmailModule = this.emailModuleList.find(
        (item) => item.id === this.form.emailModuleId
      );

      variableList = targetEmailModule.content.match(regex) || [];
      if (this.form.emailModuleId) {
        // this.$refs.templateEditor.setHTML(targetEmailModule.content || '')
        this.$refs.richEditor.clearEditor(); // 清空富文本数据
        if (!isEdit) {
          this.form.title = targetEmailModule.title;
          this.form.initialContent = targetEmailModule.content;
        }



        if (variableList.length !== 0) {
          this.domData.content = targetEmailModule.content;
          this.domData.data = this.form.data; // 回显数据
        }

        this.$refs.richEditor.insertHTML(this.form.initialContent);

        console.log(
          "[ targetEmailModule.content---------------------------------------1 ] >",
          targetEmailModule.content
        );
        if (variableList.length) {
          this.isDefault = true;
        } else {
          this.isDefault = false;
        }
      }
    },

    // emailIdChange() {
    //   const targetEmailModule = this.emailModuleList.find(
    //     (item) => item.id === this.form.emailModuleId
    //   );

    //   this.form.title = targetEmailModule.title;
    //   // this.$refs.templateEditor.setHTML(targetEmailModule.content || '')
    //   this.form.initialContent = targetEmailModule.content;
    //   this.form.content = targetEmailModule.content;
    //   this.$refs.richEditor.insertHTML(targetEmailModule.content);

    //   const regex = /\{{(.+?)\}}/g; // {{}} 匹配双花括号
    //   let variableList = this.form.initialContent.match(regex) || [];
    //   this.form.keysList = variableList.map((variable, index) => ({
    //     name: variable,
    //     id: index,
    //     key: "",
    //     expression: "",
    //   }));
    // },

    async getEmailTemplate() {
      let params = {
        currentPage: 1,
        showCount: -1,
      };
      let rs = await CanvasApi.getEmailTemplate(params);
      if (rs.code === 200) {
        this.emailModuleList = rs.payload;
      }
    },

    handleEditorChange({ innerHTML }) {

      this.form.initialContent = innerHTML;

    },

    handleCancel() {
      this.$emit("cancel");
    },

    formValidate() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.handleConfirm();
        } else {

          return false;
        }
      });
    },

    getConfigId () {
      let configId = ""
      this.emailModuleList.find(item=> {
        if(item.id === this.form.emailModuleId) {
          configId = item.configId
        }
      })
      return configId
    },

    handleConfirm() {
      // let valCheck = false;
      // let initialContent = this.form.initialContent;
      // // let initialContent = this.$refs.templateEditor.getHTML();

      // this.form.keysList.forEach((item) => {
      //   if (!item.key) {
      //     valCheck = true;
      //   }
      //   // 替换content中的字符
      //   initialContent = initialContent.replace(
      //     new RegExp(item.name, "g"),
      //     item.key
      //   );
      // });
      // if (valCheck) {
      //   this.$message.warning("请选择属性值");
      //   return;
      // }
      // this.form.content = initialContent;

      //

      this.form.content = this.form.initialContent;
      debugger
      this.$emit(
        "confirm",
        new NodeDrawerDataModel({
          dialogData: {
            name: this.form.name,
            reachBody: JSON.stringify(this.form),
            reachType: this.reachType,
            configId: this.getConfigId()
          },
        })
      );


      this.handleCancel();
    },
  },
};
</script>

<style scoped lang="scss">
.custom-input-name {
  width: 440px;
}

.custom-input-anchor-input {
  width: 104px;
}

.form-wrapper {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.custom-form {
  flex: 1;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
}
:deep(.ql-container) {
  height: 300px;
  width: 100%;
}
</style>
